<template>
  <div class="local-services-page">
    <!-- 搜索表单 -->
    <el-card class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="服务分类">
          <el-select v-model="searchForm.category_id" placeholder="请选择分类" clearable>
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="DRAFT" />
            <el-option label="已发布" value="PUBLISHED" />
            <el-option label="已下线" value="OFFLINE" />
          </el-select>
        </el-form-item>

        <el-form-item label="审核状态">
          <el-select v-model="searchForm.audit_status" placeholder="请选择审核状态" clearable>
            <el-option label="待审核" value="PENDING" />
            <el-option label="审核通过" value="APPROVED" />
            <el-option label="审核拒绝" value="REJECTED" />
          </el-select>
        </el-form-item>

        <el-form-item label="省份">
          <el-input
            v-model="searchForm.province"
            placeholder="请输入省份"
            clearable
            style="width: 120px"
          />
        </el-form-item>

        <el-form-item label="城市">
          <el-input
            v-model="searchForm.city"
            placeholder="请输入城市"
            clearable
            style="width: 120px"
          />
        </el-form-item>

        <el-form-item label="搜索关键词">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入服务标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 本地服务列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>本地同行服务列表</span>
          <div class="header-actions">
            <el-button @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="serviceList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column prop="title" label="服务标题" min-width="200" />

        <el-table-column label="分类" width="120">
          <template #default="{ row }">
            {{ row.category?.name || '未分类' }}
          </template>
        </el-table-column>

        <el-table-column label="地区" width="150">
          <template #default="{ row }">
            {{ row.province || '' }} {{ row.city || '' }}
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getAuditStatusTagType(row.audit_status)">
              {{ getAuditStatusText(row.audit_status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="保证金" width="120">
          <template #default="{ row }">
            <span v-if="row.deposit_required > 0">
              已付：¥{{ row.deposit_paid }}<br/>
              需要：¥{{ row.deposit_required }}
            </span>
            <span v-else>无需保证金</span>
          </template>
        </el-table-column>

        <el-table-column label="浏览次数" width="100">
          <template #default="{ row }">
            {{ row.view_count }}
          </template>
        </el-table-column>

        <el-table-column label="发布者手机号" width="130">
          <template #default="{ row }">
            <span v-if="row.user?.phone_number" class="phone-number">
              {{ row.user.phone_number }}
            </span>
            <span v-else class="no-phone">未填写</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="自动发布时间" width="180">
          <template #default="{ row }">
            {{ row.auto_publish_at ? formatDate(row.auto_publish_at) : '-' }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(row)"
              >
                查看详情
              </el-button>

              <el-dropdown @command="(command: string) => handleStatusChange(row, command)">
                <el-button type="warning" size="small">
                  状态操作
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="PUBLISHED" :disabled="row.status === 'PUBLISHED'">
                      设为已发布
                    </el-dropdown-item>
                    <el-dropdown-item command="OFFLINE" :disabled="row.status === 'OFFLINE'">
                      下线
                    </el-dropdown-item>
                    <el-dropdown-item command="DRAFT" :disabled="row.status === 'DRAFT'">
                      设为草稿
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <el-dropdown @command="(command: string) => handleAuditAction(row, command)">
                <el-button type="success" size="small">
                  审核操作
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="approve" :disabled="row.audit_status === 'APPROVED'">
                      审核通过
                    </el-dropdown-item>
                    <el-dropdown-item command="reject" :disabled="row.audit_status === 'REJECTED'">
                      审核拒绝
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="本地服务详情"
      width="900px"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentService" class="service-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="服务ID">
            {{ currentService.id }}
          </el-descriptions-item>
          <el-descriptions-item label="服务标题">
            {{ currentService.title }}
          </el-descriptions-item>
          <el-descriptions-item label="服务分类">
            {{ currentService.category?.name || '未分类' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentService.status)">
              {{ getStatusText(currentService.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getAuditStatusTagType(currentService.audit_status)">
              {{ getAuditStatusText(currentService.audit_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="地区">
            {{ currentService.province || '' }} {{ currentService.city || '' }}
          </el-descriptions-item>
          <el-descriptions-item label="保证金要求">
            ¥{{ currentService.deposit_required }}
          </el-descriptions-item>
          <el-descriptions-item label="已付保证金">
            ¥{{ currentService.deposit_paid }}
          </el-descriptions-item>
          <el-descriptions-item label="浏览次数">
            {{ currentService.view_count }}
          </el-descriptions-item>
          <el-descriptions-item label="发布者手机号">
            <span v-if="currentService.user?.phone_number" class="phone-number">
              {{ currentService.user.phone_number }}
            </span>
            <span v-else class="no-phone">未填写</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(currentService.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDate(currentService.updated_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="审核时间">
            {{ currentService.audit_time ? formatDate(currentService.audit_time) : '未审核' }}
          </el-descriptions-item>
          <el-descriptions-item label="自动发布时间">
            {{ currentService.auto_publish_at ? formatDate(currentService.auto_publish_at) : '无' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 联系方式 -->
        <div v-if="currentService.contact_info" class="contact-info">
          <h4>联系方式</h4>
          <p>{{ currentService.contact_info }}</p>
        </div>

        <!-- 基础服务 -->
        <div v-if="currentService.basic_services" class="basic-services">
          <h4>基础服务</h4>
          <p>{{ currentService.basic_services }}</p>
        </div>

        <!-- 增值服务 -->
        <div v-if="currentService.extended_services" class="extended-services">
          <h4>增值服务</h4>
          <p>{{ currentService.extended_services }}</p>
        </div>

        <!-- 售后服务 -->
        <div v-if="currentService.after_sale_service" class="after-sale-service">
          <h4>售后服务</h4>
          <p>{{ currentService.after_sale_service }}</p>
        </div>

        <!-- 审核意见 -->
        <div v-if="currentService.audit_comment" class="audit-comment">
          <h4>审核意见</h4>
          <p>{{ currentService.audit_comment }}</p>
        </div>

        <!-- 服务图片 -->
        <div v-if="currentService.images && currentService.images.length > 0" class="service-images">
          <h4>服务图片</h4>
          <div class="image-gallery">
            <img
              v-for="(image, index) in currentService.images"
              :key="index"
              :src="image"
              :alt="`服务图片${index + 1}`"
              class="service-image"
              @click="previewImage(image)"
            />
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 审核拒绝对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="审核拒绝"
      width="500px"
    >
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="拒绝理由" required>
          <el-input
            v-model="rejectForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmReject">确定拒绝</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, ArrowDown } from '@element-plus/icons-vue'
import { 
  localServiceApi, 
  serviceCategoryApi, 
  type LocalService, 
  type LocalServiceListParams,
  type ServiceCategory
} from '@/api/admin'

// 响应式数据
const loading = ref(false)
const serviceList = ref<LocalService[]>([])
const categories = ref<ServiceCategory[]>([])
const detailDialogVisible = ref(false)
const rejectDialogVisible = ref(false)
const currentService = ref<LocalService | null>(null)
const currentRejectService = ref<LocalService | null>(null)

// 搜索表单
const searchForm = reactive<LocalServiceListParams>({
  category_id: undefined,
  status: undefined,
  audit_status: undefined,
  province: '',
  city: '',
  search: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 拒绝表单
const rejectForm = reactive({
  comment: ''
})

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString()
}

// 获取状态标签颜色
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    'DRAFT': 'info',
    'PUBLISHED': 'success',
    'OFFLINE': 'danger'
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'DRAFT': '草稿',
    'PUBLISHED': '已发布',
    'OFFLINE': '已下线'
  }
  return statusMap[status] || status
}

// 获取审核状态标签颜色
const getAuditStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger'
  }
  return statusMap[status] || ''
}

// 获取审核状态文本
const getAuditStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '待审核',
    'APPROVED': '审核通过',
    'REJECTED': '审核拒绝'
  }
  return statusMap[status] || status
}

// 获取服务分类列表
const getCategories = async () => {
  try {
    const response = await serviceCategoryApi.getList()
    categories.value = response.data || []
  } catch (error) {
    console.error('获取服务分类失败:', error)
  }
}

// 获取本地服务列表
const getServiceList = async () => {
  loading.value = true
  try {
    const params: LocalServiceListParams = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    const response = await localServiceApi.getList(params)
    serviceList.value = response.data
    pagination.total = response.pagination.total
  } catch (error) {
    console.error('获取本地服务列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getServiceList()
}

// 重置搜索
const handleReset = () => {
  searchForm.category_id = undefined
  searchForm.status = undefined
  searchForm.audit_status = undefined
  searchForm.province = ''
  searchForm.city = ''
  searchForm.search = ''
  pagination.page = 1
  getServiceList()
}

// 刷新
const handleRefresh = () => {
  getServiceList()
}

// 查看详情
const handleViewDetail = async (service: LocalService) => {
  try {
    const response = await localServiceApi.getDetail(service.id)
    currentService.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取服务详情失败:', error)
  }
}

// 关闭详情对话框
const handleCloseDetail = () => {
  detailDialogVisible.value = false
  currentService.value = null
}

// 状态变更
const handleStatusChange = async (service: LocalService, status: string) => {
  try {
    const statusText = getStatusText(status)
    await ElMessageBox.confirm(`确定要将服务 "${service.title}" 设为${statusText}吗？`, `确认操作`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await localServiceApi.updateStatus(service.id, status as any)
    ElMessage.success(`状态更新成功`)
    getServiceList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('状态变更失败:', error)
    }
  }
}

// 审核操作
const handleAuditAction = async (service: LocalService, action: string) => {
  if (action === 'approve') {
    try {
      await ElMessageBox.confirm(`确定要审核通过服务 "${service.title}" 吗？`, '确认审核', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      })

      await localServiceApi.approve(service.id)
      ElMessage.success('审核通过成功')
      getServiceList()
    } catch (error: any) {
      if (error !== 'cancel') {
        console.error('审核通过失败:', error)
      }
    }
  } else if (action === 'reject') {
    currentRejectService.value = service
    rejectForm.comment = ''
    rejectDialogVisible.value = true
  }
}

// 确认拒绝
const confirmReject = async () => {
  if (!rejectForm.comment.trim()) {
    ElMessage.warning('请输入拒绝理由')
    return
  }

  try {
    await localServiceApi.reject(currentRejectService.value!.id, rejectForm.comment)
    ElMessage.success('审核拒绝成功')
    rejectDialogVisible.value = false
    currentRejectService.value = null
    getServiceList()
  } catch (error) {
    console.error('审核拒绝失败:', error)
  }
}

// 删除
const handleDelete = async (service: LocalService) => {
  try {
    await ElMessageBox.confirm(`确定要删除服务 "${service.title}" 吗？此操作不可恢复！`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })

    await localServiceApi.delete(service.id)
    ElMessage.success('删除成功')
    getServiceList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 预览图片
const previewImage = (src: string) => {
  // 这里可以使用 Element Plus 的图片预览组件
  window.open(src, '_blank')
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  getServiceList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  getServiceList()
}

// 初始化
onMounted(() => {
  getCategories()
  getServiceList()
})
</script>

<style scoped>
.local-services-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.service-detail {
  padding: 20px 0;
}

.contact-info,
.basic-services,
.extended-services,
.after-sale-service,
.audit-comment {
  margin-top: 20px;
}

.contact-info h4,
.basic-services h4,
.extended-services h4,
.after-sale-service h4,
.audit-comment h4,
.service-images h4 {
  margin-bottom: 10px;
  color: #303133;
}

.contact-info p,
.basic-services p,
.extended-services p,
.after-sale-service p,
.audit-comment p {
  line-height: 1.6;
  color: #606266;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.service-images {
  margin-top: 20px;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.service-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

.service-image:hover {
  border-color: #409eff;
  transform: scale(1.05);
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .local-services-page {
    padding: 15px;
  }

  .el-table {
    font-size: 12px;
  }

  .el-pagination {
    text-align: center;
  }

  .el-dialog {
    width: 95% !important;
  }

  .action-buttons {
    gap: 4px;
  }

  .action-buttons .el-button {
    font-size: 11px;
    padding: 4px 8px;
  }
}

.phone-number {
  color: #606266;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
}

.no-phone {
  color: #C0C4CC;
  font-style: italic;
  font-size: 12px;
}
</style>